﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Diagnostics;

using Styx.Common;
using Styx.CommonBot;
using Styx.TreeSharp;

namespace GatherBroDllLoader
{
    public class GatherBroLoader : BotBase
    {
        private static string FolderLocation = Path.Combine(Utilities.AssemblyDirectory, "Bots\\" + DirectoryLocator("GatherBro.dll"));
        private static readonly string DllLocation = Path.Combine(FolderLocation, "GatherBro.dll");
        private readonly Assembly _botDll;
        private readonly BotBase _botBase;

        public override string Name { get { return _botBase.Name; } }
        public override bool IsPrimaryType { get { return _botBase.IsPrimaryType; } }
        //public override bool RequirementsMet { get { return _botBase.RequirementsMet; } }
        public override void Initialize() { _botBase.Initialize(); }
        public override void Start() { _botBase.Start(); }
        public override void Stop() { _botBase.Stop(); }
        public override void Pulse() { _botBase.Pulse(); }
        public override Composite Root { get { return _botBase.Root; } }
        public override Form ConfigurationForm { get { return _botBase.ConfigurationForm; } }
        public override PulseFlags PulseFlags { get { return _botBase.PulseFlags; } }
        public GatherBroLoader()
        {
            try
            {
                var directory = DirectoryLocator("GatherBro.dll");
                AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
                {
                    try
                    {
                        AssemblyName requestedName = new AssemblyName(e.Name);
                        //Logging.Write(requestedName.FullName);
                        if (requestedName.Name == "Honorbuddy")
                        {
                            //Logging.Write("Loading " + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                            return Assembly.LoadFile(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                        }
                        if (requestedName.Name == "GreyMagic")
                        {
                            //Logging.Write("Loading " + Utilities.AssemblyDirectory + @"\GreyMagic.dll");
                            return Assembly.LoadFile(Utilities.AssemblyDirectory + @"\GreyMagic.dll");
                        }
                        return null;
                    }
                    catch (System.Exception)
                    {
                        return null;
                    }
                };
                if (File.Exists(FolderLocation + "\\BuddyPluginsAutoUpdater.exe"))
                {
                    string[] args = { "Guest", "Guest", "GatherBro", String.Format("\"" + FolderLocation + "\"") };
                    var p = new Process
                    {
                        StartInfo =
                        {
                            FileName = Path.Combine(FolderLocation, "BuddyPluginsAutoUpdater.exe"),
                            Arguments = String.Join(" ", args)
                        }
                    };
                    p.Start();
                }
                _botDll = Assembly.LoadFrom(DllLocation);
                var typeOfBot = _botDll.GetTypes().FirstOrDefault(t => typeof(BotBase).IsAssignableFrom(t));
                if (typeOfBot != null)
                    _botBase = (BotBase)Activator.CreateInstance(typeOfBot);
                else
                    Logging.Write("GatherBroLoader: Missing BotBase type in dll: {0}", DllLocation);
            }
            catch (Exception ex)
            {
                Logging.Write("GatherBroLoader: {0}", ex);
            }
        }

        private static string DirectoryLocator(string fileName)
        {
            try
            {
                foreach (
                    string file in
                        Directory.EnumerateFiles(Utilities.AssemblyDirectory + @"\Bots\", fileName,
                                                 SearchOption.AllDirectories))
                {
                    return new FileInfo(file).Directory.Name;
                }
                Logging.Write("Please make sure Gather Bro is installed Correctly.!");
                return "";
            }
            catch
            {
                Logging.Write("Directory Location Failure");
                return "";
            }
        }
    }
}